import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/article_item.dart';
import 'package:flutter_syt/datas/provider_index_setting.dart';
import 'package:flutter_syt/datas/venue_item.dart';
import 'package:flutter_syt/domain/games/venue_subcription_item.dart';
import 'package:flutter_syt/domain/waystation/map_helper.dart';
import 'package:flutter_syt/domain/widgets/flow_item.dart';
import 'package:flutter_syt/domain/widgets/network_load_image.dart';
import 'package:flutter_syt/domain/widgets/photo_views_more_screen.dart';
import 'package:flutter_syt/domain/widgets/tab_indicator.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/fade_route.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
// import 'package:webview_flutter/webview_flutter.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '../../routes.all.dart';

class VenueDetailEntity {
  int id;
  String name;
  String address;
  String cover;
  String detail;
  String long;
  String lat;

  VenueDetailEntity(this.id, this.name, this.address, this.cover, this.detail,
      this.long, this.lat);
}

@RoutePage(name: "venueDetailPage")
class VenueDetailPage extends StatefulWidget {
  final String id;

  VenueDetailPage(this.id);

  @override
  _VenueDetailPageState createState() => _VenueDetailPageState();
}

class _VenueDetailPageState extends State<VenueDetailPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  ScrollController _scrollviewController = ScrollController();
  bool isLoading = true;
  VenueItem? data;
  String? error;
  InAppWebViewController? _webViewController;
  List<ArticleListItem> news = [];
  List<VenueSubscriptionEntity> subs = [];
  double _height = 1.sh;
  // LocationData? _locationData;
  String? _distance;
  @override
  void initState() {
    _tabController = TabController(
        length: ProviderIndexSetting().indexSetting.gameSchedule == 1 ? 3 : 2,
        vsync: this);
    getData();

    super.initState();
  }

  void getData() async {
    setState(() {
      isLoading = true;
    });
    try {
      data = await API.shared.venue.detail(widget.id);
      news = await API.shared.venue.newsList(widget.id);
      subs = await API.shared.venue.gameList(widget.id);
      // startLocation();
      error = null;
    } catch (e, stack) {
      error = "$e";
      debugPrint("$stack");
    }
    setState(() {
      isLoading = false;
    });
  }

  // startLocation() async {
  //   try {
  //     LocationHelper.instance.result((LocationData event) async {
  //       if (event.location?.latitude != null) {
  //         _locationData = event;
  //       }
  //       calculationDistance();
  //     });
  //     await LocationHelper.instance.startLocation();
  //   } catch (e) {}
  // }

  // calculationDistance() async {
  //   if (_locationData != null && data?.lat != 0) {
  //     var distance = UtilsComment.getDistance(
  //         BMFCoordinate(_locationData?.location?.latitude ?? 0.0,
  //             _locationData?.location?.longitude ?? 0.0),
  //         BMFCoordinate(data?.lat ?? 0.0, data?.long ?? 0.0));
  //     if (mounted) {
  //       setState(() {
  //         _distance = (distance / 1000).toStringAsFixed(2);
  //       });
  //     }
  //   } else {
  //     _distance = null;
  //   }
  // }

  Widget loading() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            "assets/icons/empty.png",
            width: 80,
            height: 80,
          ),
          Container(
            height: 12,
          ),
          Text(
            S.of(context).loading,
            style:
                TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 14),
          ),
          Container(
            height: 20,
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Image.asset(
              "assets/images/black_back.png",
              width: 30,
              height: 30,
            ),
            onPressed: ClickUtils.debounce(() {
              Navigator.of(context).pop();
            }),
          ),
        ),
        body: Center(
          child: loading(),
        ),
      );
    }
    if (error != null) {
      return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Image.asset(
              "assets/images/black_back.png",
              width: 30,
              height: 30,
            ),
            onPressed: ClickUtils.debounce(() {
              Navigator.of(context).pop();
            }),
          ),
        ),
        body: ViewStateErrorWidget(
          onPressed: ClickUtils.debounce(() {
            getData();
          }),
        ),
      );
    }
    var hasData = data;
    if (hasData == null) {
      return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Image.asset(
              "assets/images/black_back.png",
              width: 30,
              height: 30,
            ),
            onPressed: ClickUtils.debounce(() {
              Navigator.of(context).pop();
            }),
          ),
        ),
        body: ViewStateErrorWidget(
          onPressed: ClickUtils.debounce(() {
            getData();
          }),
        ),
      );
    }
    // var width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: NestedScrollView(
        controller: _scrollviewController,
        headerSliverBuilder: (context, boxIsScrolled) {
          return [
            SliverAppBar(
              leading: IconButton(
                icon: Image.asset(
                  "assets/images/black_back.png",
                  width: 30,
                  height: 30,
                ),
                onPressed: ClickUtils.debounce(() {
                  Navigator.of(context).pop();
                }),
              ),
              pinned: true,
              floating: true,
              elevation: 0.5,
              forceElevated: true,
              // primary: true,
              backgroundColor: Colors.white,
              expandedHeight: 1.sw,
              flexibleSpace: FlexibleSpaceBar(
                collapseMode: CollapseMode.pin, //视差效果
                background: Container(
                  // height: 200.w,
                  // width: 1.sw,
                  margin: EdgeInsets.only(bottom: 44.w),
                  child: Stack(
                    children: [
                      Positioned.fill(
                          child: GestureDetector(
                        onTap: () {
                          Navigator.of(context).push(
                            FadeRoute(
                                page: PhotoViewMoreScreen(
                              imageRows: [
                                hasData.cover,
                              ],
                            )),
                          );
                        },
                        child: ClipRRect(
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(20),
                              bottomRight: Radius.circular(20)),
                          child: Container(
                            color: Colors.white,
                            // height: 1.sw,
                            // width: 1.sw,
                            child: NetworkLoadImage.loadNetworkImage(
                              //  CachedNetworkImage(
                              // imageUrl:
                              hasData.cover,
                              // errorWidget: (ctx, err, trace) {
                              //   return Container(
                              //     color: Colors.grey.withOpacity(0.7),
                              //   );
                              // },
                              fit: BoxFit.cover,
                            ),
                          ),
                          // borderRadius: const BorderRadius.only(
                          //   bottomRight: Radius.circular(20),
                          //   bottomLeft: Radius.circular(20),
                          // ),
                        ),
                      )),
                      Positioned.fill(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Container(
                              height: 120,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.only(
                                      bottomLeft: Radius.circular(20),
                                      bottomRight: Radius.circular(20)),
                                  gradient: LinearGradient(
                                    colors: [
                                      Color(0xff131313).withOpacity(0.75),
                                      Color(0xff1b1b1b).withOpacity(0.41),
                                      Color(0x00242424),
                                    ],
                                    begin: Alignment.bottomCenter,
                                    end: Alignment.topCenter,
                                  )),
                            ),
                          ],
                        ),
                      ),
                      Positioned.fill(
                        child: Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 16, vertical: 20),
                            child: Row(
                              children: [
                                Expanded(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        hasData.name,
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 24,
                                        ),
                                      ),
                                      Text(
                                        hasData.address,
                                        style: TextStyle(
                                          color: Colors.white.withOpacity(0.8),
                                          fontSize: 14,
                                        ),
                                      ),
                                      // Text(
                                      //   hasData.address,
                                      //   style: TextStyle(
                                      //     color: Colors.white.withOpacity(0.79),
                                      //     fontSize: 14,
                                      //   ),
                                      // ),
                                    ],
                                  ),
                                ),
                                // SizedBox(
                                //   width: 10,
                                // ),
                                // GestureDetector(
                                //     child: Column(
                                //       mainAxisAlignment: MainAxisAlignment.end,
                                //       children: [
                                //         Image.asset(
                                //           'assets/images/image_event_map.png',
                                //           width: 20,
                                //           height: 20,
                                //         ),
                                //         SizedBox(
                                //           height: 4,
                                //         ),
                                //         Text(
                                //           '${_distance ?? "-"}km',
                                //           style: TextStyle(
                                //             fontSize: 12,
                                //             color: ThemeColor.bkColorFFFFFF,
                                //           ),
                                //         ),
                                //       ],
                                //     ),
                                //     onTap: ClickUtils.debounce(() {
                                //       MapNavigatorUtil.showBottom(context,
                                //           latitude:
                                //               (data?.lat ?? 0.0).toString(),
                                //           longitude:
                                //               (data?.long ?? 0.0).toString());
                                //     }))
                              ],
                            )),
                      ),
                    ],
                  ),
                ),
              ),
              bottom:
                  // NormalTabs(
                  //        [
                  //               ScrollerTabEntity.create(
                  //                   'type', S.current.search_information, 0, ''),
                  //               ScrollerTabEntity.create(
                  //                   'type', S.current.search_site, 0, ''),
                  //               ScrollerTabEntity.create(
                  //                   'type', S.current.search_project, 0, ''),
                  //               ScrollerTabEntity.create(
                  //                   'type', S.current.search_schedule, 0, '')
                  //             ]
                  //           ,
                  //       _tabController,
                  //       // textColor: Colors.black,
                  //       // alignment: Alignment.centerLeft,
                  //     ),
                  TabBar(
                      labelColor: Colors.black,
                      controller: _tabController,
                      indicatorPadding:
                          const EdgeInsets.symmetric(horizontal: 10),
                      tabs: [
                        if (ProviderIndexSetting().indexSetting.gameSchedule ==
                            1)
                          Tab(
                            text: S.of(context).Schedule,
                          ),
                        Tab(
                          text: S.of(context).Introduction,
                        ),
                        Tab(
                          text: S.of(context).Announcement,
                        ),
                      ],
                      isScrollable: true,
                      indicator: LinearGradientTabIndicatorDecoration(
                        borderSide: BorderSide(
                            width: 3, color: const Color(0xFFFFD833)),
                        insets: EdgeInsets.only(left: 20, right: 20),
                        gradient: const LinearGradient(
                          colors: [
                            const Color(0xFFFFD833),
                            const Color(0xFFFFD833)
                          ],
                        ),
                        isRound: true,
                      )),
            ),
          ];
        },
        body: TabBarView(
          controller: _tabController,
          children: [
            if (ProviderIndexSetting().indexSetting.gameSchedule == 1)
              _buildSub(),
            SingleChildScrollView(
                child: Container(
              height: _height,
              child: InAppWebView(
                initialUrlRequest:
                    URLRequest(url: WebUri.uri(Uri.parse(buildUrl(data?.detail ?? '')))),
                // initialData:
                // InAppWebViewInitialData(data: (data?.detail ?? '')),
                // initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
                onLoadStop: (controller, url) {
                  controller
                      .evaluateJavascript(
                          source: 'document.documentElement.clientHeight;')
                      .then((result) {
                    DLog('result  $result');
                    if (mounted) {
                      setState(() {
                        _height = double.parse("$result");
                        DLog("高度result $_height");
                      });
                    }
                  });
                  //   ?.runJavascriptReturningResult(
                  //       "document.documentElement.clientHeight;")
                  //   .then((result) {
                  // if (mounted) {
                  //   setState(() {
                  //     _height = double.parse(result);
                  //     print("高度$result");
                  //   });
                  // }
                  // });
                },
                onWebViewCreated: (InAppWebViewController controller) {
                  _webViewController = controller;
                  controller.addJavaScriptHandler(
                    handlerName: "checkFullSize",
                    callback: (arguments) {
                      DLog("arguments + $arguments");
                      if (arguments.isNotEmpty) {
                        Map<String, dynamic> json = arguments.first;
                        // var str = arguments.first.toString();
                        // Map<String, dynamic> json = convert.jsonDecode(str);
                        // convert.jsonDecode();
                        if (json.keys.contains('urls')) {
                          List<String> lists = [];
                          json['urls'].forEach((element) {
                            lists.add(element.toString());
                          });
                          Navigator.of(context).push(
                            FadeRoute(
                                page: PhotoViewMoreScreen(
                              imageRows: lists,
                              defaultImage: json['default'] is int
                                  ? json['default']
                                  : (int.tryParse(json['default']) ?? 0),
                            )),
                          );
                        }
                      }
                    },
                  );
                  // _webViewController.r
                  // _webViewController.evaluateJavascript(
                  //     source:
                  //         "document.documentElement.style.webkitTouchCallout='none';");
                  // _webViewController.evaluateJavascript(
                  //     source:
                  //         "document.documentElement.style.webkitUserSelect='none';");
                },
              ),
              // child: WebView(
              //   gestureNavigationEnabled: true,
              //   onWebViewCreated: (controller) {
              //     _webViewController = controller;
              //     // controller.loadUrl(buildUrl(data?.detail ?? ''));
              //     // controller.loadHtmlString(buildUrl(data?.detail ?? ''));
              //   },
              //   initialUrl: buildUrl(data?.detail ?? ''),
              //   javascriptMode: JavascriptMode.unrestricted,
              //   onPageFinished: (url) {
              //     _webViewController
              //         ?.runJavascriptReturningResult(
              //             "document.documentElement.clientHeight;")
              //         .then((result) {
              //       if (mounted) {
              //         setState(() {
              //           _height = double.parse(result);
              //           print("高度$result");
              //         });
              //       }
              //     });
              //   },
              // ),
            )),
            if (news.length == 0)
              Container(
                child: Center(
                  child: ViewStateEmptyWidget(),
                ),
              )
            else
              ListView.builder(
                itemBuilder: (ctx, index) {
                  ArticleListItem item = news[index];
                  var entity = FlowItemEntity();
                  entity.createTime = item.publish_time;
                  entity.text = item.title;
                  entity.imageUrl = item.thumb;
                  entity.labelText = "";
                  return GestureDetector(
                    child: FlowItem(entity),
                    onTap: () => RouteManager.push(context, item.linkUrl),
                  );
                },
                itemCount: news.length,
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildSub() {
    if (subs.length == 0) {
      return Container(
        child: Center(
          child: ViewStateEmptyWidget(),
        ),
      );
    } else {
      return ListView.builder(
        padding: EdgeInsets.only(top: 0),
        itemBuilder: (ctx, index) {
          VenueSubscriptionEntity item = subs[index];
          return GestureDetector(
            child: VenueSubscriptionItem(item),
            onTap: ClickUtils.debounce(() => RouteManager.push(
                context,
                RoutMapping.gameDetail(item.id,
                    isVideo: false, isVenue: true))),
          );
        },
        itemCount: subs.length,
      );
    }

    // if (ProviderIndexSetting().indexSetting.gameSchedule == 1)
  }

  String buildUrl(String body) {
    var content = '''
<html>

<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
   $body
</body>
</html>
    ''';
    return Uri.dataFromString(content,
            mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
        .toString();
    // return content;
  }
}
